package java.awt;

import java.awt.image.BufferedImage;

import javax.accessibility.Accessible;

import org.cb.core.Global;
import org.cb.core.ScriptBase;


@SuppressWarnings("serial")
public class Canvas extends Component implements Accessible {
	private BufferedImage image;
	public boolean shouldPaint = true;
	ScriptBase script;
	
	public Canvas() {        
		image = new BufferedImage(765, 503, BufferedImage.TYPE_INT_ARGB);
	}

	public void setPaintOn() {shouldPaint = true;}
	public void setPaintOff() {shouldPaint = false;}
	
	@Override
	public Graphics getGraphics() {
		Graphics buffer = image.getGraphics();
		
		if(Global.isLoaded()) {
			if(this.getMouseMotionListeners().length > 0) {
				if(getMousePosition() != null && !Global.getTheMouse().mouseMoving) {
					Global.getTheMouse().mouseXY = getMousePosition();
				}
			}
				
			if(shouldPaint && Global.isLoaded()) {
				if(script != null)
					try {
						script.paint(buffer);
					} catch (InterruptedException e) {e.printStackTrace();}
					
				if(Global.isPaintMouse()){
					buffer.drawLine(0, Global.getTheMouse().mouseXY.y, 765, Global.getTheMouse().mouseXY.y);
					buffer.drawLine(Global.getTheMouse().mouseXY.x, 0, Global.getTheMouse().mouseXY.x, 503);
					buffer.drawImage(Global.getMouseIcon(), Global.getTheMouse().mouseXY.x - 20, Global.getTheMouse().mouseXY.y - 20, 40, 40, null);
				}
			}
		}
		
		super.getGraphics().drawImage(image, 0, 0, null);
		return image.createGraphics();
	}
	
	public BufferedImage getImage() {
		BufferedImage img = new BufferedImage(765, 503, BufferedImage.TYPE_INT_RGB);
		img.getGraphics().drawImage(image, 0, 0, 765, 503, 0, 0, 765, 503, null);
		return img;
	}
	
	public BufferedImage getImage(Rectangle r){
		BufferedImage img = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_RGB);
		img.getGraphics().drawImage(image, r.x, r.y, r.width, r.height, r.x, r.y, r.width, r.height, null);
		return img;
	}
	
	public void setScript(ScriptBase sc){
		script = sc;
	}
}